import { Body, Controller, Get, Post, Req } from '@nestjs/common'
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger'
import { Public } from '@/decorators/public.decorator'
import { UsersService } from '@/users/users.service'
import { AuthUserDto } from './dto/auth-user.dto'
import { AuthService } from './auth.service'

@Controller('auth')
@ApiTags('认证授权模块')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly usersService: UsersService
  ) {}

  @Post('/login')
  @ApiBody({ type: AuthUserDto })
  @ApiOperation({ summary: '登录' })
  @Public()
  async signin(@Body() authUserDto: AuthUserDto) {
    const userInfo = await this.authService.signin(authUserDto)
    return userInfo
  }

  @Get('/getUserInfo')
  @ApiOperation({ summary: '获取登录的用户信息' })
  async getUserInfo(@Req() req: ReqPayload) {
    console.log('req.user', req.user)
    const userInfo = await this.usersService.findOneById(req.user.userId, {
      relations: ['roles', 'roles.role', 'roles.role.permissions'],
    })
    console.log('userInfo', userInfo)
    const roles = userInfo.roles.map((userRole) => userRole.role.roleCode)
    const buttons = userInfo.roles
      .map((userRole) => userRole.role.permissions.map((permission) => permission.permissionCode))
      .flat()
    return {
      userId: userInfo.id,
      userName: userInfo.userName,
      roles,
      buttons,
    }
  }
}
